<?php

/**
 * MLEPP - ManiaLive Extending Plugin Pack
 *
 * -- MLEPP Plugin --
 * @name TMX-info getter
 * @date 19-02-2011
 * @version r854
 * @website mlepp.trackmania.nl
 * @package MLEPP
 *
 * @author Petri "reaby" Järvisalo <petri.jarvisalo@mbnet.fi>
 *         Guy "Knutselmaaster" Van Der Zel <knutselmaaster@gmail.com>
 *
 * @copyright 2010 - 2011
 *
 * ---------------------------------------------------------------------
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 * You are allowed to change things or use this in other projects, as
 * long as you leave the information at the top (name, date, version,
 * website, package, author, copyright) and publish the code under
 * the GNU General Public License version 3.
 * ---------------------------------------------------------------------
 */

namespace ManiaLivePlugins\MLEPP\TmxInfo;

use ManiaLive\Utilities\Console;
use ManiaLive\Utilities\String;
use ManiaLive\DedicatedApi\Connection;
use ManiaLive\PluginHandler\PluginHandler;
use ManiaLivePlugins\MLEPP\TmxInfo\Gui\Windows\SimpleWindow;
use ManiaLivePlugins\MLEPP\Core\Core;
use ManiaLive\Data\Storage;
use ManiaLive\Event\Dispatcher;

class TmxInfo extends \ManiaLive\PluginHandler\Plugin {

    /**
     * onInit()
     * Function called on initialisation of ManiaLive.
     *
     * @return void
     */

	function onInit() {
		$version = 854;
		$this->setVersion($version);
		$this->setPublicMethod('showTMXinfo');
        $this->setPublicMethod('getVersion');

        //ML Repository
        if(Core::RepositoryId != null){
            $this->setRepositoryId(Core::RepositoryId);
            $this->setRepositoryVersion(Core::RepositoryVersion);
        }

		//Oliverde8 Menu
		if($this->isPluginLoaded('oliverde8\HudMenu')) {
			Dispatcher::register(\ManiaLivePlugins\oliverde8\HudMenu\onOliverde8HudMenuReady::getClass(), $this);
		}
	}

    /**
     * onLoad()
     * Function called on loading of ManiaLive.
     *
     * @return void
     */

	function onLoad() {
		$this->enableDedicatedEvents();
        Console::println('['.date('H:i:s').'] [MLEPP] Plugin: TmxInfo r'.$this->getVersion().' by reaby, W1lla & Knutselmaaster.');
		$command = $this->registerChatCommand("tmxinfo", "showTMXinfo", 0, true);
	}

	/**
	 * onReady()
     * Function called when ManiaLive is ready loading.
     * -- Not used (yet?) --
	 *
	 * @return void
	 */

	function onReady() {

	}

	/**
	 * onOliverde8HudMenuReady()
     * Function used for adding buttons to Olivers Hud Menu.
	 *
	 * @param mixed $menu
	 * @return void
	 */
	public function onOliverde8HudMenuReady($menu) {
		$parent = $menu->findButton(array("Menu","Tracks and JB"));

        if(!$parent){
            //caption="Tracks and JB" style="Icons128x128_1" substyle="ProfileVehicle"
            $button["style"]="Icons128x128_1";
            $button["substyle"]="ProfileVehicle";

            $parent = $menu->addButton("Menu", "Tracks and JB",$button);
        }

		$button["image"]=Core::$widget_graphics_tmx;
		$button["plugin"] = $this;
		$button["function"] = "showTMXinfo";
		$parent = $menu->addButton($parent, "Show TMX Info",$button);
	}

	/**
	 * getHTTPdata()
     * Function used for getting TMX data.
	 *
	 * @param mixed $url
	 * @return
	 */

	function getHTTPdata($url) {
		$options = array('http' => array(
                         'user_agent'    => 'manialive tmx-getter',        // who am i
                         'max_redirects' => 1000,              // stop after 10 redirects
                         'timeout'       => 1000,             // timeout on response
                    ));
        $context = stream_context_create( $options );

        return @file_get_contents( $url, true, $context );
    }

	/**
	 * showTMXinfo()
     * Function providing the TMX Info window.
	 *
	 * @param mixed $login
	 * @param mixed $plugin
	 * @return void
	 */

	function showTMXinfo($login, $plugin = null) {

        $found = false;
        $prefixes = array('tmnforever', 'nations', 'united', 'sunrise', 'original');
        foreach($prefixes as $prefix) {
            if($found === false) {
                $tmxData = $this->getHTTPdata('http://'.$prefix.'.tm-exchange.com/apiget.aspx?action=apitrackinfo&uid='.Storage::getInstance()->currentChallenge->uId);
                if($tmxData == 0) {
                    $found = false;
                } else {
    				$found = true;
					break;
                }
            }
        }

        if($found === false) {
            $player = Storage::GetInstance()->getPlayerObject($login);
            $this->connection->chatSendServerMessage('$fff»» The requested track was not found on TMX', $player);
        } else {
            $data = explode("\t",$tmxData);
            $window = SimpleWindow::Create($login);
            $window->setSize(80, 60);
            $window->setData($data);
			$window->setTargetTmx($prefix);
            $window->centerOnScreen();
            $window->Show();
        }
    }
}
?>